package Tool;


import static Tool.AppTool.GetTime;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkCapabilities;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.Message;
import android.text.format.Formatter;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.StringTokenizer;
import java.util.regex.Pattern;

public class NetTool {
    /**
     * @param context
     * @return {@link String}
     *///获取设备IP
    public static String Getip(Context context) {
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int ipAddress = wifiInfo.getIpAddress();

        String ip = Formatter.formatIpAddress(ipAddress);
        return ip;
    }

    /**
     * 判断当前网络是否可用(6.0以上版本)
     * 实时
     *
     * @param context
     * @return
     */
    public static boolean isNetSystemUsable(Context context) {
        boolean isNetUsable = false;
        ConnectivityManager manager = (ConnectivityManager)
                context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            NetworkCapabilities networkCapabilities =
                    manager.getNetworkCapabilities(manager.getActiveNetwork());
            if (networkCapabilities != null) {
                isNetUsable = networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI);
            }

        }
        return isNetUsable;
    }

    /**
     * @return
     * @category 判断是否有外网连接（普通方法不能判断外网的网络是否连接，比如连接上局域网）
     */
    public static final boolean ping(String ip) {
        if (ip == null) {
            ip = "www.baidu.com";// ping 的地址，可以换成任何一种可靠的外网
        }
        String result = null;
        try {
            Process p = Runtime.getRuntime().exec("ping -c 1 -w 100 " + ip);// ping网址3次
            // 读取ping的内容，可以不加
            InputStream input = p.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(input));
            StringBuffer stringBuffer = new StringBuffer();
            String content = "";
            while ((content = in.readLine()) != null) {
                stringBuffer.append(content);
            }
            // ping的状态
            int status = p.waitFor();
            if (status == 0) {
                result = "success";
                return true;
            } else {
                result = "failed";
            }
        } catch (IOException e) {
            result = "IOException";
        } catch (InterruptedException e) {
            result = "InterruptedException";
        }
        return false;
    }

    /**
     * @param link
     * @param handler
     *///Http请求
    public void networdRequest(String link, Handler handler,String linkmsg) {

        String way = "POST";
        if (link.equals("http://login.hnust.cn/drcom/chkstatus?callback=dr1003")) {
            way = "GET";
        } else {
            way = "POST";
        }
        HttpURLConnection connection = null;
        try {
            URL url = new URL(link);
            connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(3000);
            connection.setReadTimeout(3000);
            connection.setRequestMethod(way);
            connection.setDoInput(true);
            connection.setDoOutput(false);
            connection.connect();
            int responseCode = connection.getResponseCode();
            if (responseCode != HttpURLConnection.HTTP_OK) {
                throw new IOException("HTTP error code" + responseCode);
            }
            String result = getStringByStream(connection.getInputStream());
            if (result == null) {
                System.out.println("\n操作时间:"+GetTime());
                System.out.println("访问原因: "+linkmsg);
                System.out.println(linkmsg+"访问链接: "+link);
                Log.d("Fail", "http失败");
            } else {
                System.out.println("\n操作时间:"+GetTime());
                System.out.println("访问原因: "+linkmsg);
                System.out.println("访问链接: "+link);
                System.out.println(linkmsg+"HTTP结果: "+result);
            }
            Message msg1 = new Message();
            if (link.equals("http://login.hnust.cn/drcom/chkstatus?callback=dr1003")) {
                msg1.what = 1;
            } else {
                msg1.what = 0;  //消息(一个整型值)
            }
            msg1.obj = result;
            handler.sendMessage(msg1);
        } catch (Exception e) {
            Message msg1 = new Message();
            msg1.what = 1;
            msg1.obj = null;
            handler.sendMessage(msg1);
            e.printStackTrace();
        }
    }

    private String getStringByStream(InputStream inputStream) {
        Reader reader;
        try {
            reader = new InputStreamReader(inputStream, "UTF-8");
            char[] rawBuffer = new char[1024];
            StringBuffer buffer = new StringBuffer();
            int length;
            while ((length = reader.read(rawBuffer)) != -1) {
                buffer.append(rawBuffer, 0, length);
            }
            return buffer.toString();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getConnectWifiSsid(Context context) {
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        assert wifiManager != null;

        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        String SSID = wifiInfo.getSSID();

        return SSID.replace("\"", "");
    }
    public static String getError(String str)
    {
        String []RadiusErrorAry= new String[55];
        RadiusErrorAry[0]= "Oppp error: Timeout 40|运营商账号异常";
        RadiusErrorAry[1]= "Rpost=2;ret='Authentication Fail ErrCode=05'|您的账号已停机";
        RadiusErrorAry[2]= "err(2)|您的账号不能在此区域内登录";
        RadiusErrorAry[3]= "err(3)|请在指定的IP登录";
        RadiusErrorAry[4]= "err(7)|请在指定的登录源VLAN范围登录";
        RadiusErrorAry[5]= "userid error2|账号密码输入错误";
        RadiusErrorAry[6]= "userid error3|密码错误";
        RadiusErrorAry[7]= "auth error5|账号已停机";
        RadiusErrorAry[8]= "auth error99|用户名或密码错误";
        RadiusErrorAry[9]= "auth error198|用户名或密码错误";
        RadiusErrorAry[10]="auth error199|用户名或密码错误";
        RadiusErrorAry[11]="auth error258|请在指定的登录源内登录";
        RadiusErrorAry[12]="Mac, IP, NASip, PORT err(6)|本帐号只能在指定VLANID使用";
        RadiusErrorAry[13]="Rpost=2;ret='wuxian OLno|VLAN范围控制账号的接入数量超出限制";
        RadiusErrorAry[14]="Oppp error: 1|运营商账号密码错误";
        RadiusErrorAry[15]="Oppp error: 18|运营商账号密码错误";
        RadiusErrorAry[16]="Oppp error: 21|运营商账号在线";
        RadiusErrorAry[17]="Oppp error: 26|运营商账号被绑定";
        RadiusErrorAry[18]="Oppp error: 29|运营商账号锁定的用户端口NAS-Port-Id错误";
        RadiusErrorAry[19]="Oppp error: userid inuse|运营商账号已被使用";
        RadiusErrorAry[20]="Oppp error: can't find user|运营商账号无法获取或不存在";
        RadiusErrorAry[21]="bind userid error|绑定运营商账号失败";
        RadiusErrorAry[22]="Rad:Oppp error: TOO MANY CONNECTIONS|运营商账号在线";
        RadiusErrorAry[23]="Rad:Oppp error: Timeout|运营商账号状态异常";
        RadiusErrorAry[24]="Oppp error: User dial-in so soon|运营商账号刚下线";
        RadiusErrorAry[25]="Rad:Oppp error: RD104|您的移动宽带帐号(或开通此账号的电话卡)欠费或停机";
        RadiusErrorAry[26]="Rad:Oppp error: RD205|中国移动运营商账号验证错误";
        RadiusErrorAry[27]="Authentication Fail ErrCode=11|计费组不允许radius登陆";
        RadiusErrorAry[28]="Oppp error: [Code 2]: Package is not legal|数据包不合法";
        RadiusErrorAry[29]="Authentication Fail ErrCode=05|校园网帐号已停机";
        RadiusErrorAry[30]="Authentication Fail ErrCode=16|此时间段不允许登录";
        RadiusErrorAry[31]="Mac, IP, NASip, PORT err(29)!|学生宿舍区访问校内免费,请办理运营商网络";
        RadiusErrorAry[32]=".*radius.*response.*|此运营商认证服务器无响应";
        RadiusErrorAry[33]="Rad:Oppp error: [Code 4]: User status is not RUN|您的运营商账号(或开通此账号的电话卡)欠费或停机";
        RadiusErrorAry[34]="Authentication fail|账号输入错误或相关线路系统维护中";
        RadiusErrorAry[35]="no errcode|你已经登录啦";
        RadiusErrorAry[36]="Rad:Oppp error: 2|您的运营商账号(或开通此账号的电话卡)欠费或停机";
        RadiusErrorAry[37]="Rad:Oppp error: 34|错误34";
        RadiusErrorAry[38]="Mac, IP, NASip, PORT err(2)!|您的账号不能在此(虚拟范围)内登录";
        RadiusErrorAry[39]="Rad:Oppp error: [Code 30]: Too many access|请稍后再重试登录";
        RadiusErrorAry[40]="userid error1|未绑定此运营商";
        RadiusErrorAry[41]="Rad:Oppp error: 5|在线设备已经有两台啦";
        RadiusErrorAry[42]="Rad:Oppp error: RD103|运营商账号密码错误";
        RadiusErrorAry[43]="Rad:Oppp error: RD203|运营商账号密码错误";
        RadiusErrorAry[44]="Rad:Oppp error: RD204|在线设备已经有两台啦";
        RadiusErrorAry[45]="Rad:Oppp error: 99|联通服务器登录失败,客服:【1-4区】18673201003【5-8区】15675257773";
        RadiusErrorAry[46]="Rad:Oppp error: RD102|运营商账号密码错误";
        RadiusErrorAry[47]="Rad:Oppp error: [Code 3]: Unable to find user in database|运营商账号密码错误";
        RadiusErrorAry[48]="Rad:Oppp error: [Code 5]: User password error|运营商账号密码错误";
        RadiusErrorAry[49]="Rad:Oppp error: [Code 6]: Max user number exceed|在线设备已经有两台啦";
        RadiusErrorAry[50]="Rad:Oppp error: Timeout 40|此运营商服务器无响应";
        RadiusErrorAry[51]="Rad:Oppp error: 1|运营商账号密码错误";
        RadiusErrorAry[52]="Rad:Oppp error: 44|联通服务器登录失败";
        RadiusErrorAry[53]="Rad:Oppp error: 09026004.109020109.*|在线设备已经有两台啦";
        RadiusErrorAry[54]="Rad:Oppp error: 109026002.109020122.*|此联通宽带账号状态异常或已停机";
        for (int i=0;i<=54;i++)
        {
            StringTokenizer st = new StringTokenizer(RadiusErrorAry[i], "|");
            String[] arrOfStr = new String[st.countTokens()];
            int n = 0;
            while (st.hasMoreTokens()) {
                arrOfStr[n++] = st.nextToken();
            }
            if (arrOfStr[0].equals(str))
            {
                return arrOfStr[1];
            }
        }
        return "未知错误,登录失败";
    }

    public  static boolean isBase64(String str) {
        String base64Pattern = "^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$";
        return Pattern.matches(base64Pattern, str);
    }
    public  static boolean  judgeUnicode(String str)
    {
        return str.matches("\\p{InCJKUnifiedIdeographs}+");

    }
}
